package com.zchi.customizeAuthentication.security.smsCode;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description TODO
 * @Author 张弛
 * @Datee 2021/7/4
 * @Version 1.0
 **/
@Slf4j
@RestController
public class SmsValidateCodeController {

    public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";

//    @GetMapping("/code/sms")
//    public void createSmsCode(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletRequestBindingException {
//        ValidateCode validateCode = smsCodeGenerate.generate(request);
//        String mobile = ServletRequestUtils.getRequiredStringParameter(request, "mobile");
//        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, validateCode.getCode());
//        smsCodeSender.send(mobile, validateCode.getCode());
//    }

    @GetMapping("/user/captcha")
    public void getcaptchaUrl(HttpServletRequest request, HttpServletResponse response) {
        try {
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 50);
            lineCaptcha.createCode();
            // todo 保存验证码

            System.out.println("》》》》》》》》》》》》" + lineCaptcha.getCode());
            request.getSession().setAttribute("code", lineCaptcha.getCode());
            ImageIO.write(lineCaptcha.getImage(), "JPEG", response.getOutputStream());
        } catch (IOException e) {
            log.error("获取验证码出错", e);
        }
    }
}
